package com.zyl.blog.common.handler;

import com.zyl.blog.common.enums.OperationType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.handler
 * @ClassName: OperationTypeHandler
 * @Description
 * @Author FinalFantasy
 * @Date 2025/2/17-20:23
 */
public class OperationTypeHandler extends BaseTypeHandler<OperationType> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    OperationType parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, String.valueOf(parameter.getCode()));
    }

    @Override
    public OperationType getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String code = rs.getString(columnName);
        return code == null ? null : parseCode(code);
    }

    @Override
    public OperationType getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        String code = rs.getString(columnIndex);
        return code == null ? null : parseCode(code);
    }

    @Override
    public OperationType getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String code = cs.getString(columnIndex);
        return code == null ? null : parseCode(code);
    }

    private OperationType parseCode(String codeStr) {
        try {
            int code = Integer.parseInt(codeStr);
            return OperationType.fromCode(code);
        } catch (NumberFormatException e) {
            throw new TypeException("非法的操作类型代码格式: " + codeStr, e);
        }
    }
}